package com.pointcircle.core.web.annotation;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.pointcircle.core.entity.User;
import com.pointcircle.core.entity.OperationLog;
import com.pointcircle.core.repository.OperationLogRepository;
import com.pointcircle.core.web.auth.AuthUtils;

@Component
@Aspect
public class OperationLogAspect {
	
	@Autowired
	private OperationLogRepository operationLogRepository;
	
	@After("@annotation(OperationLogAnnotation)")
	public void record(JoinPoint jp) throws JSONException {
		User user = AuthUtils.getUser();
		HttpServletRequest request = 
			((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		JSONObject json = new JSONObject();
		for(String parameter : request.getParameterMap().keySet()) {
			String[] values = request.getParameterValues(parameter);
			if(values.length == 1) {
				json.put(parameter, values[0]);
			} else if(values.length > 1) {
				JSONArray array = new JSONArray(values);
				json.put(parameter, array);
			}
		}
		String content = "修改数据：(" + request.getRequestURI() + ")" + json.toString();
		OperationLog log = new OperationLog();
		log.setUserId(user.getId());
		log.setLogTime(new Date());
		log.setContent(content);
		log.setIp(request.getRemoteAddr());
		operationLogRepository.saveAndFlush(log);
	}
}
